package com.sand.service.Imp;

import com.alibaba.fastjson.JSON;
import com.sand.dao.IBaseDao;
import com.sand.entity.*;
import com.sand.service.IAuthService;
import com.sand.util.PageModel;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@Service(value = "authService")
public class AuthServiceImp implements IAuthService {
/**
 *权限控制层
 *
 * @author <achao1441470436@gmail.com>
 * @since 2021/11/28/028 14:56
 */
    //Dao层接口
    @Resource(name = "baseDao")
    private IBaseDao baseDao;

    /**
     * 根据用户查询角色，根据角色查询所有权限
     * 将权限列表存入作用域，返回权限列表字符串
     *
     * @param user
     * @return
     */
    @Override
    public String queryAuthByUser(TUserEntity user, HttpServletRequest request) {
        HttpSession session = request.getSession();
        //存放权限
        Set<TAuthorityEntity> set = new LinkedHashSet<TAuthorityEntity>();
        //如果为1号用户，拥有所有权限
        if(user.getRid()==1){
            List<TAuthorityEntity> list = baseDao.queryObject("from TAuthorityEntity");
            set.addAll(list);
        }
        //分级查询
        List<TRoleuserEntity> list1 = baseDao.queryObject("from TRoleuserEntity t where t.userId="+user.getRid());
        if(list1!=null){
            for(TRoleuserEntity r:list1){
                List<TAuthorityEntity> list2 = baseDao.queryObject("select ta from TRoleauthEntity tra,TAuthorityEntity ta where tra.roleId=" + r.getRoleId() + " and tra.authId=ta.rid");
                set.addAll(list2);
            }
        }

        //将权限存入作用域，返回字符串权限列表
        session.setAttribute("userAuth",set);
        StringBuffer str1=new StringBuffer("{\n" +
                "  \"homeInfo\": {\n" +
                "    \"title\": \"首页\",\n" +
                "    \"href\": \"page/welcome-1.html?t=1\"\n" +
                "  },\n" );
        //基本参数
        if(set!=null){
            int no1=0;
            int no2=0;
            int no3=0;
            int count1=0;
            int count2=0;
            int count3=0;
            //计算一级菜单的总条数
            for (TAuthorityEntity a4 : set) {
                if(a4.getParentId()==1){
                    count1++;
                }
                if(a4.getParentId()==0){
                    str1.append(                "  \"logoInfo\": {\n" +
                            "    \"title\": \""+a4.getName()+"\",\n" +
                            "    \"image\": \"images/hide.jpg\",\n" +
                            "    \"href\": \"\"\n" +
                            "  },\n" +
                            "  \"menuInfo\": [\n" +
                            "    {\n" +
                            "      \"title\": \"常规管理\",\n" +
                            "      \"icon\": \"fa fa-address-book\",\n" +
                            "      \"href\": \"\",\n" +
                            "      \"target\": \"_self\",\n" +
                            "      \"child\": [\n");
                }
            }
            //开始遍历查找一级菜单
            for (TAuthorityEntity a : set) {
                if(a.getParentId()==1){
                    count2=0;
                    no1++;
                    str1.append("        {\n" +
                            "          \"title\": \""+a.getName()+"\",\n" +
                            "          \"icon\": \"fa fa-navicon\",\n" +
                            "          \"target\": \"_self\"\n" );
                    //计算二级菜单的总条数
                    for (TAuthorityEntity a2_1 : set) {
                        if(a2_1.getParentId()==a.getRid() && a2_1.getIsMenu()==1){
                            count2++;
                        }
                    }
                    //开始遍历查找二级菜单
                    for (TAuthorityEntity a2 : set) {
                        if(a2.getParentId()==a.getRid() && a2.getIsMenu()==1){
                            if(no2==0){
                                str1.append(",\"child\": [\n");
                            }
                            count3=0;
                            no2++;
                            str1.append("            {\n" +
                                    "              \"title\": \""+a2.getName()+"\",\n" +
                                    "              \"href\": \""+a2.getUrl()+"\",\n" +
                                    "              \"icon\": \"fa fa-navicon\",\n" +
                                    "              \"target\": \"_self\"\n");
                            //计算三级菜单的总条数
                            for (TAuthorityEntity a3_1 : set) {
                                if(a3_1.getParentId()==a2.getRid() && a3_1.getIsMenu()==1){
                                    count3++;
                                }
                            }
                            //开始遍历查找三级菜单
                            for (TAuthorityEntity a3 : set) {
                                if(a3.getParentId()==a2.getRid() && a3.getIsMenu()==1){
                                    if(no3==0){
                                        str1.append(",\"child\": [\n");
                                    }
                                    no3++;
                                    str1.append("            {\n" +
                                            "              \"title\": \""+a3.getName()+"\",\n" +
                                            "              \"href\": \""+a3.getUrl()+"\",\n" +
                                            "              \"icon\": \"fa fa-navicon\",\n" +
                                            "              \"target\": \"_self\"\n");
                                    if(no3==count3){
                                        str1.append("          } ");
                                    }else{
                                        str1.append("          }, ");
                                    }
                                }
                            }
                            if(no3!=0){
                                str1.append("          ]");
                                no3=0;
                            }
                            if(no2==count2){
                                str1.append("          } ");
                            }else{
                                str1.append("          }, ");
                            }
                        }
                    }
                    if(no2!=0){
                        str1.append("          ]");
                        no2=0;
                    }
                    if(no1==count1){
                        str1.append("          } ");
                    }else{
                        str1.append("          }, ");
                    }
                }
            }
            str1.append("      ]\n" +
                    "    }\n" +
                    "  ]\n" +
                    "}");
        }
        return str1.toString();
    }

    /**
     * 根据角色Id查询所有权限
     *
     * @param id
     * @return
     */
    @Override
    public List<TAuthorityEntity> queryAuthByRoleId(int id) {
        List<TAuthorityEntity> authList = new ArrayList<>();
        //查询角色对应的权限
        List<TRoleauthEntity> list = baseDao.queryObject("from TRoleauthEntity t where t.roleId=" + id);
        if(list!=null){
            for (TRoleauthEntity t : list) {
                //根据权限ID查询权限
                List<TAuthorityEntity> list2 = baseDao.queryObject("from TAuthorityEntity t where t.rid=" + t.getAuthId());
                if(list2!=null){
                    authList.add(list2.get(0));
                }
            }
        }
        return authList;
    }

    /**
     * 跟级别查询所有权限
     *
     * @return
     */
    @Override
    public List<Map<String, Object>> queryAuthLevelAll() {
        List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();

        //查询一级菜单
        List<TAuthorityEntity> list1 = baseDao.queryObject("from TAuthorityEntity t where t.menuLevel=1");

        for (TAuthorityEntity a:list1){
            //存放一级权限菜单
            Map<String,Object> map=new HashMap<String,Object>();
            map.put("one",a);
            //查询一级菜单下的子菜单》二级菜单
            List<TAuthorityEntity> list2 = baseDao.queryObject("from TAuthorityEntity t where t.parentId=" + a.getRid());

            List<Map<String,Object>> list3=new ArrayList<Map<String,Object>>();
            for(TAuthorityEntity b:list2){
                //存放二级菜单
                Map<String,Object> map2=new HashMap<String,Object>();
                map2.put("two",b);

                //查询二级菜单下的子菜单》三级菜单
                List<TAuthorityEntity> list4 =baseDao.queryObject("from TAuthorityEntity t where t.parentId="+b.getRid());

                List<Map<String,Object>> list5=new ArrayList<Map<String,Object>>();
                for(TAuthorityEntity c:list4){
                    //存放三级菜单
                    Map<String,Object> map3=new HashMap<String,Object>();
                    map3.put("three",c);
                    //查询二级菜单下的子菜单》三级菜单
                    List<TAuthorityEntity> list6 =baseDao.queryObject("from TAuthorityEntity t where t.parentId="+c.getRid());
                    map3.put("threeList",list6);
                    list5.add(map3);
                }

                map2.put("twoList",list5);
                list3.add(map2);

            }
            map.put("oneList",list3);
            list.add(map);
        }
        return list;
    }

    //查询所有权限
    @Override
    public List<TAuthorityEntity> queryAuthAll() {
        return baseDao.queryObject("from TAuthorityEntity");
    }

    //分页查询
    @Override
    public PageModel<TAuthorityEntity> queryAuthLimit(int limit, int page, String condition) {
        PageModel<TAuthorityEntity> pm = new PageModel<TAuthorityEntity>();
        //计算开始位置
        int begin=(page-1)*limit;
        //创建查询对象
        DetachedCriteria dc = DetachedCriteria.forClass(TAuthorityEntity.class);
        //添加模糊查询条件
        if(condition!=null){
            dc.add(Restrictions.like("name","%"+condition+"%"));
        }
        //查询总条数
        List<Long> list1 = baseDao.queryObjectCommon(dc.setProjection(Projections.rowCount()));
        //清空条件
        dc.setProjection(null);
        //设置排序
        dc.addOrder(Order.desc("rid"));
        //分页查询
        List<TAuthorityEntity> list = baseDao.queryObjectLimit(dc, begin, limit);
        long i=list1.get(0);
        int count= (int) i;

        List<TAuthorityEntity> list2 = this.queryAuthAll();
        if(list2!=null && list!=null){
            for (TAuthorityEntity t : list) {
                for (TAuthorityEntity r : list2) {
                    if(t.getParentId()==r.getRid()){
                        t.setParentIdView(r.getName());
                    }
                }
            }
        }

        pm.setList(list);
        pm.setPageNo(page);
        pm.setPageSize(limit);
        pm.setPagecount(count);
        return pm;
    }

    //根据id查询权限
    @Override
    public TAuthorityEntity queryAuthById(int id) {
        TAuthorityEntity auth = (TAuthorityEntity) baseDao.queryObjectById(TAuthorityEntity.class, id);
        List<TAuthorityEntity> list2 = this.queryAuthAll();
        if(list2!=null && auth!=null){
            for (TAuthorityEntity r : list2) {
                if(auth.getParentId()==r.getRid()){
                    auth.setParentIdView(r.getName());
                }
            }
        }
        return auth;
    }
    //添加权限
    @Override
    public boolean addAuth(String data) {
        if(data!=null){
            TAuthorityEntity auth = JSON.parseObject(data, TAuthorityEntity.class);
            boolean bln = baseDao.addObject(auth);
            if(bln){
               return true;
            }
        }
        return false;
    }
    //修改权限
    @Override
    public boolean updateAuth(String data) {
        if(data!=null){
            TAuthorityEntity auth = JSON.parseObject(data, TAuthorityEntity.class);
            boolean bln = baseDao.updateObject(auth);
            if(bln){
               return true;
            }
        }
        return false;
    }
    //删除权限
    @Override
    public boolean delAuth(String data) {
        if(data!=null){
            //解析json数据
            List<TAuthorityEntity> list = JSON.parseArray(data, TAuthorityEntity.class);
            boolean bln = baseDao.delAllObject(list);
            if(bln){
                return true;
            }
        }
        return false;
    }
}
